;(function(window, document, angular, undefined){
    var HTTP_URL = (!BASE_URL||BASE_URL=='')?'/' :BASE_URL ;
	var app = angular.module('ng-chooser',['cfp.loadingBar']);

	angular.module("ng-chooser").run(["$templateCache", function($templateCache) {
		$templateCache.get('/templates/choose-person.html');
		$templateCache.get('/templates/choose-department.html');
		$templateCache.get('/templates/choose-advanced.html');
	}]);

    app.factory('ApiUtil', ['$http', '$q', function ($http, $q) {
        var URL_PREFIX = '';

        var request_method = {
            /**
             * @description ApiUtil 参数配置
             * @function config
             * @memberof ng.poler.ApiUtil
             * @param {Object} config
             *  {<br>
             *      URL_PREFIX: {String} 请求地址统一前缀<br>
             *  }<br>
             */
            config: function (config) {
                if (config.hasOwnProperty('URL_PREFIX') && angular.isDefined(config.URL_PREFIX)) {
                    URL_PREFIX = config.URL_PREFIX;
                }
            },
            /**
             * @description ApiUtil 请求方法
             * @function request
             * @memberof ng.poler.ApiUtil
             * @param url {String} http 请求接口地址
             * @param method {string} http 接口请求方法 (如 'GET', 'POST', 等)
             * @param params {Object.<string|Object>} http 请求查询参数
             * @param data {string|Object} http 请求发送数据
             * @param config {object.<string|Object|function>} http 请求配置参数<br>
             *  <b>headers {Object.<string|functions>} <br> </b>
             *  &nbsp;&nbsp;&nbsp;
             *      字符串或者函数返回的字符串放入http请求头部发送到服务器。如果函数返回null，这个头部信息不会发送。<br>
             *  <b>xsrfHeaderName {string} <br></b>
             *  &nbsp;&nbsp;&nbsp;
             *      http 头部信息中 XSRF token 头部的名字<br>
             *  <b>xsrfCookieName {string} <br></b>
             *  &nbsp;&nbsp;&nbsp;
             *      cookie中包含 XSRF token 信息的名字<br>
             *  <b>transformRequest {function(data, headersGetter)|Array.<function(data, headersGetter)>}<br></b>
             *  &nbsp;&nbsp;&nbsp;
             *      请求头部和请求body 转换处理函数。会覆盖默认的转换处理函数。<br>
             *  <b>transformResponse {function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} <br></b>
             *  &nbsp;&nbsp;&nbsp;
             *      响应 body，headers，status转换出事函数。会覆盖默认的转换处理函数<br>
             *  <b>cache {boolean|Cache} <br> </b>
             *  &nbsp;&nbsp;&nbsp;
             *      是否缓存。当 cache=true，使用 $http 的缓存；当 cache 为 $cacheFactory 的实例时，用cache进行缓存<br>
             *  <b>timeout {number|Promise} <br> </b>
             *  &nbsp;&nbsp;&nbsp;
             *      请求超时设置。可以是毫秒数，也可以是一个promise，当为promise时，应该在promise得到解决的时候停止请求。<br>
             *  <b>withCredentials {boolean} <br> </b>
             *  &nbsp;&nbsp;&nbsp;
             *      设置这个 withCredentials 标记到 XHR 对象中，withCredentials 标记时候使用跨越cookie。更对关于withCredentials请查看相关文档。<br>
             *  <b>responseType {string} <br> </b>
             *  &nbsp;&nbsp;&nbsp;
             *      返回数据类型。更多信息请查看 requestType。
             * @returns {Promise} 返回一个承诺，使用angularjs 的 $q 服务产生
             *
             * @example post 请求
             *      ApiUtil.request('http://127.0.0.1:3000/test','POST', {
             *              aa:'aa'
             *          },
             *          "test data",
             *          {
             *              headers:{
             *                  aaa: "aaa",
             *                  bbb: function() { return "bbb"; },
             *                  ccc: function{} { return "ccc"; }
             *              },
             *              withCredentials: true
             *          }
             *      )
             *
             * @example get 请求
             *      ApiUtil.request('http://127.0.0.1:3000/test','GET', {
             *              aa:'aa'
             *          },
             *          "test data",
             *          {
             *              headers:{
             *                  aaa: "aaa",
             *                  bbb: function() { return "bbb"; },
             *                  ccc: function{} { return "ccc"; }
             *              },
             *              withCredentials: true
             *          }
             *      )
             */
            request: function (url, method, params, data, config) {
                var deferred = $q.defer();
                var req_config = config || {};

                if (!/http[s]?:\/\/.*/.test(url)) {
                    url = URL_PREFIX + url;
                }
                params = params || {};

                // request data
                $http({
                    method: method,
                    url: url,
                    params: params,
                    data: data,
                    timeout: req_config.timeout
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);
                }).error(function (data, status, headers, config) {
                    deferred.reject(data);
                });

                return deferred.promise;
            },
            /**
             * @description 封装 [request]{@link ng.poler.ApiUtil.request} 的 POST 请求方法
             * @function post
             * @memberof ng.poler.ApiUtil
             * @param {string} url    [参考request.url]{@link ng.poler.ApiUtil.request}
             * @param {Object} params [参考request.params]{@link ng.poler.ApiUtil.request}
             * @param {Object} config [参考request.config]{@link ng.poler.ApiUtil.request}
             * @returns {promise}     [参考 request 返回值]{@link ng.poler.ApiUtil.request}
             */
            post: function (url, params, config) {
                return request_method.request(url, 'POST', null, params, config);
            },
            /**
             * @description 封装 [request]{@link ng.poler.ApiUtil.request} 的 GET 请求方法
             * @function get
             * @memberof ng.poler.ApiUtil
             * @param {string} url    [参考request.url]{@link ng.poler.ApiUtil.request}
             * @param {Object} params [参考request.params]{@link ng.poler.ApiUtil.request}
             * @param {Object} config [参考request.config]{@link ng.poler.ApiUtil.request}
             * @returns {promise}     [参考 request 返回值]{@link ng.poler.ApiUtil.request}
             */
            get: function (url, params, config) {
                return request_method.request(url, 'GET', params, null, config);
            },
            /**
             * @description 封装 [request]{@link ng.poler.ApiUtil.request} 的 DELETE 请求方法
             * @function del
             * @memberof ng.poler.ApiUtil
             * @param {string} url    [参考request.url]{@link ng.poler.ApiUtil.request}
             * @param {Object} params [参考request.params]{@link ng.poler.ApiUtil.request}
             * @param {Object} config [参考request.config]{@link ng.poler.ApiUtil.request}
             * @returns {promise}     [参考 request 返回值]{@link ng.poler.ApiUtil.request}
             */
            delete: function (url, params, config) {
                return request_method.request(url, 'DELETE', null, params, config);
            },
            /**
             * @description 封装 [request]{@link ng.poler.ApiUtil.request} 的 PATCH 请求方法
             * @function patch
             * @memberof ng.poler.ApiUtil
             * @param {string} url    [参考request.url]{@link ng.poler.ApiUtil.request}
             * @param {Object} params [参考request.params]{@link ng.poler.ApiUtil.request}
             * @param {Object} config [参考request.config]{@link ng.poler.ApiUtil.request}
             * @returns {promise}     [参考 request 返回值]{@link ng.poler.ApiUtil.request}
             */
            patch: function (url, params, config) {
                return request_method.request(url, 'PATCH', null, params, config);
            },
            /**
             * @description 封装 [request]{@link ng.poler.ApiUtil.request} 的 PUT 请求方法
             * @function put
             * @memberof ng.poler.ApiUtil
             * @param {string} url    [参考request.url]{@link ng.poler.ApiUtil.request}
             * @param {Object} params [参考request.params]{@link ng.poler.ApiUtil.request}
             * @param {Object} config [参考request.config]{@link ng.poler.ApiUtil.request}
             * @returns {promise}     [参考 request 返回值]{@link ng.poler.ApiUtil.request}
             */
            put: function (url, params, config) {
                return request_method.request(url, 'PUT', null, params, config);
            }
        };

        return request_method;
    }]);
    app.factory('ChoosePublicMethod', [function() {
        return {
            /**
             * 动态设置弹窗title
             * @param params  Array
             */
            _bindChooseWhat: function(params) {
                var obj = {},
                    defaultTitle= [
                        { what1: '部门'},
                        { what2: '人员'}
                    ];
                for(var i = 0; i < defaultTitle.length; i++) {
                    for (var k in defaultTitle[i]) {
                        obj[k] = defaultTitle[i][k];
                    }
                }
                if(params) {
                    for(var i=0; i < params.length; i++) {
                        for (var k in params[i]) {
                            obj[k] = params[i][k];
                        }
                    }
                }else {
                    return obj;
                }
                return obj;
            }
        }
    }]);
    app.factory('ChoosePersonService',['$http', '$q', 'ApiUtil', 'ChoosePublicMethod',function($http, $q, ApiUtil,ChoosePublicMethod){
        return {
            department: function (p) {
                return ApiUtil.get(HTTP_URL+'admin/public/departments', p);
            },
            member: function (p) {
                return ApiUtil.get(HTTP_URL+'admin/public/users', p);
            },
            tag: function(p) {
                return ApiUtil.get(HTTP_URL+'admin/public/tags', p);
            },
            bindChooseWhat: function(p) {
                return ChoosePublicMethod._bindChooseWhat.call(null, p);
            }
        }
    }]);

    /**
     * 选人组件控制器
     */
    app.controller('ChoosePersonCtrl',['$scope','$window','ApiUtil','ChoosePersonService','cfpLoadingBar',function ($scope,$window,ApiUtil,ChoosePersonService,cfpLoadingBar) {
        $scope.allDep = {};
        $scope.noMembers = false;
        var depTree = [];
        var checkSuccess = function(data){
        	try {
                return data['errCode'] == 0;
            } catch (e) {
                return false;
            }
        };
        var getWhat = ChoosePersonService.bindChooseWhat($scope.chooseWhat);
        for(var k in getWhat) {
            $scope[k] = getWhat[k];
        }
        function eachTreeNode(nodeList, childField, fn) {
	        if(nodeList instanceof Array){
	            for(var dli=0; dli<nodeList.length; dli++) {
	                var itDep = nodeList[dli];
	                fn && fn(itDep);
	                if(itDep[childField]) {
	                    eachTreeNode(itDep[childField], childField, fn);
	                }
	            }
	        }
	    }
        var init = function initFun(){
            cfpLoadingBar.start();
            $scope.departmentList = ChoosePersonService.department($scope.depQuery).then(function (data) {
                cfpLoadingBar.complete();
                if(checkSuccess(data)) {
                    depTree = $scope.departmentList = data.result.list;
                    $scope.departmentList[0]['isRoot'] = true ;
                    eachTreeNode(data.result.list,'sub',function(dep){
                    	dep.noChild = true;
                        if(dep.sub&&angular.isArray(dep.sub)&&dep.sub.length>0) { 
                            dep.noChild = false;
                        }
                        $scope.allDep[dep.de_wxid] = dep;
                    });
                    if($scope.departmentList.length>0) {
                        $scope.memberQuery.de_wxid = $scope.departmentList[0].de_wxid;
                    }
                    refreshMember();
                }
            }, function (error) {
                cfpLoadingBar.complete();
                console.log("选人组件.请求部分信息错误", error)
            });

            if(angular.isArray($scope.selectedList)) {
                $scope.selectedMembers = $scope.selectedList;
                for(var i in $scope.selectedMembers) {
                    $scope.selectedMembers[i].selected = true;
                }
            }
        };


        /**
         * 部分查询操作
         */
        $scope.depQuery = { 
            kw:''
        };
        $scope.isSearchDep = false;
        // 显示隐藏子部门
        $scope.toggleDep = function (id) {
            // 已经加载过数据，不再加载
            var curDep = $scope.allDep[id];
            curDep.isOpen = !curDep['isOpen'];

            // 检查是否需要请求
            if((curDep.sub && curDep.sub.length>0) || curDep.noChild) {
                return;
            }

            $scope.depQuery.de_wxid = id;
            //$scope.depQuery._identifier = $window.application_info.identifier;
            ChoosePersonService.department($scope.depQuery).then(function (data) {
                if(checkSuccess(data)) {
                    var departments = data.result['list'];
                    if(departments.length>0) {
                        for(var index in departments) {
                            var dep = departments[index];
                            dep.noChild = false;
                            $scope.allDep[dep.de_wxid] = dep;
                        }

                        curDep.sub = departments;
                    } else {
                        curDep.noChild = true;
                    }
                }
            }, function (error) {
                console.log("选人组件.请求部分信息错误", error)
            });
        };
        // enter键搜索
        $scope.checkSearchDep = function (event) {
            if(!$scope.depQuery.kw|| $scope.depQuery.kw=='') {
                // 没有搜索内容
                return;
            }
            if(event.keyCode==13) { // 输入enter键
                cfpLoadingBar.start();
                ChoosePersonService.department($scope.depQuery).then(function (data) {
                    cfpLoadingBar.complete();
                    if(checkSuccess(data)) {
                        $scope.departmentList = data.result.list;
                        for(var i in $scope.departmentList) {
                            $scope.departmentList[i].noChild = true;
                        }
                    }
                    $scope.isSearchDep = true;
                }, function (error) {
                    cfpLoadingBar.complete();
                    console.log("选人组件.请求部分信息错误", error)
                });

            }
        };

        /**
         * 取消搜索部门
         */
        $scope.cancelSearchDep = function () {
            $scope.departmentList = depTree;
            $scope.depQuery.kw = null;
            $scope.isSearchDep = false;
        };

        /**
         * 人员查询操作
         * @param dep
         */
        $scope.memberQuery = {
            page:1
            //_identifier:$window.application_info.identifier
        };
        var refreshMember = function () {
            cfpLoadingBar.start();
            $scope.members = ChoosePersonService.member($scope.memberQuery).then(function (data) {
                cfpLoadingBar.complete();
                $scope.members = data.result.data;
                $scope.hasMore = $scope.members.length<data.result.total;
                for(var index in data.result.data) {
                    for(var j in $scope.selectedMembers) {
                        if($scope.selectedMembers[j].g_uid == data.result.data[index].g_uid) {
                            $scope.selectedMembers[j] = data.result.data[index]
                            $scope.selectedMembers[j].selected = true;
                            break;
                        }
                    }
                }
                if($scope.members.length==0){
                    $scope.noMembers = true;
                } else {
                    $scope.noMembers = false;
                }
            }, function (error) {
                cfpLoadingBar.complete();
                console.log("选人组件.请求人员信息错误", error)
            })
        };

        // 加载更多人员
        $scope.moreMembers = function () {
            $scope.memberQuery.page += 1;
            cfpLoadingBar.start();
            ChoosePersonService.member($scope.memberQuery).then(function (data) {
                cfpLoadingBar.complete();
                for(var index in data.result.data) {
                    $scope.members.push(data.result.data[index]);
                    for(var j in $scope.selectedMembers) {
                        if($scope.selectedMembers[j].g_uid == data.result.data[index].g_uid) {
                            data.result.data[index].selected = true;
                            break;
                        }
                    }
                }
                $scope.hasMore = $scope.members.length<data.result.total;
            }, function (error) {
                cfpLoadingBar.complete();
                console.log("选人组件.请求人员信息错误", error)
            })
        };
        // 弹击部分
        $scope.clickDepartment = function (dep_id) {
            $scope.memberQuery.page = 1;
            $scope.memberQuery.de_wxid = dep_id;
            refreshMember();
        };
        //
        $scope.checkSearchMember = function (event) {
            if(event.keyCode==13) { // 输入enter键
                $scope.memberQuery.page = 1;
                refreshMember();
            }
        };
        $scope.cancelSearchMember = function () {
            $scope.memberQuery.page = 1;
            $scope.memberQuery.kw = null;
            refreshMember();
        };
        /**
         * 选择人员操作
         */
        $scope.selectedMembers = [];
        $scope.fatherDom = $(".per-item-Wrap");
        $scope.delDomItem = $(".per-item-Wrap .sel-dpm-item");
        $scope.cumulationWidth = 0;
        $scope.initWidth = 65;

        /**
         * 增加宽度(内容宽度超出父容器宽度出现滚动条)
         */
        $scope.setContentWidth = function(width){

            var contentWidth = width;
            $scope.delDomItem.css({
                width:contentWidth + 10
            });
            if( contentWidth >= 465 ){
                $scope.fatherDom.css({
                    width : 465
                });
            }
            if( contentWidth < 465 ){
                $scope.fatherDom.css({
                    width : contentWidth + 10
                });
            }

        }

        if($scope.selectedList){
            $scope.cumulationWidth = $scope.selectedList.length * $scope.initWidth;
            $scope.setContentWidth($scope.cumulationWidth);
        }

        $scope.clickMembers = function (index) {
            var sm = $scope.members[index];
            sm.selected = !sm.selected;
            if(sm.selected) { //
                if($scope.singleSelect) {
                    $scope.selectedMembers.forEach(function (obj) {
                        obj.selected = false;
                    });
                    $scope.selectedMembers.length = 0;
                }
                $scope.selectedMembers.push(sm);
            } else {  // 取消
                for(var i in $scope.selectedMembers) {
                    if(sm.g_uid==$scope.selectedMembers[i].g_uid) {
                        $scope.selectedMembers.splice(i, 1);
                        break;
                    }
                }
            }
            $scope.cumulationWidth = $scope.initWidth * $scope.selectedMembers.length;
            $scope.setContentWidth($scope.cumulationWidth);
        };
        $scope.deleteMember = function (index) {
            $scope.selectedMembers[index].selected = false;
            $scope.cumulationWidth -= $scope.initWidth;
            $scope.setContentWidth($scope.cumulationWidth);
            if($scope.members) {
                for(var j in $scope.members) {
                    if($scope.members[j].g_uid == $scope.selectedMembers[index].g_uid) {
                        $scope.members[j].selected = false;
                        break;
                    }
                }
            }

            $scope.selectedMembers.splice(index, 1);
        };
        /**
         * 判断是否选择人员
         * @param member
         * @returns {boolean}
         */
        function isSelected(member) {
            var len = $scope.selectedMembers.length;
            for(var i=0; i<len; i++) {
                var m = $scope.selectedMembers[i];
                if(m.g_uid == member.g_uid) {
                    return true;
                }
            }
            return false;
        }
        /**
         * 全部选择
         */
        $scope.selectAll = function () {
            //$scope.selectedMembers = [];
            for(var index in $scope.members) {
                $scope.members[index].selected = true;
                if(!isSelected($scope.members[index])) {
                    $scope.selectedMembers.push($scope.members[index]);
                }
            }
            $scope.cumulationWidth = $scope.selectedMembers.length * $scope.initWidth;
            $scope.setContentWidth($scope.cumulationWidth);
        };
        /**
         * 全部取消
         */
        $scope.cancelAll = function () {
            $scope.selectedMembers = [];
            $scope.cumulationWidth = 0;
            $scope.setContentWidth($scope.cumulationWidth);
            for(var index in $scope.members) {
                $scope.members[index].selected = false;
            }
        };
        /**
         * 反选
         */
        $scope.selectReverse = function () {
            $scope.selectedMembers = [];
            for(var index in $scope.members) {
                $scope.members[index].selected = !$scope.members[index].selected;
                if($scope.members[index].selected) {
                    $scope.selectedMembers.push($scope.members[index]);
                }
            }
            if($scope.selectedMembers.length){
                $scope.cumulationWidth = $scope.selectedMembers.length * $scope.initWidth;
            }else{
                $scope.cumulationWidth = 0;
            }
            $scope.setContentWidth($scope.cumulationWidth);
        };

        /**
         * 确认选择
         * @constructor
         */
        $scope.OK = function () {
            $scope.doOk($scope.selectedMembers);
        };

        init();
    }]);
    /**
     * 选人组件对外服务
     */
    app.factory('PersonChooser', ['$q','$modal',function ($q,$modal) {
        return {
            choose: function (selected,size,params) {
                var defer = $q.defer();
                var modalInstance = $modal.open({
                    templateUrl: 'templates/choose-person.html',
                    size: size || 'lg',
                    resolve: {
                        selected: function () {
                            return selected?JSON.parse(JSON.stringify(selected)):null;
                        },
                        params: function () {
                            return params || {};
                        }
                    },
                    controller:['$scope', '$modalInstance','selected','params',function ($scope, $modalInstance, selected,params) {
                        for(var k in params) {
                            $scope[k] = params[k];
                        }
                        $scope.selectedList = selected;

                        $scope.doOk = function (res) {
                            $modalInstance.close(res);
                        };
                        $scope.doCancel = function (res) {
                            $modalInstance.dismiss(res || 'cancel');
                        };
                    }]
                });

                modalInstance.opened.then(function(){//模态窗口打开之后执行的函数
                    //console.log('modal is opened');
                });
                modalInstance.result.then(function (result) {
                    defer.resolve(result);
                }, function (reason) {
                    defer.reject(reason);
                });

                return { result:defer.promise };
            }
        };
    }]);
    /**
     * 选部门组件控制器
     */
    app.controller('ChooseDepartCtrl',['$scope','$window','ApiUtil','ChoosePersonService','cfpLoadingBar',
        function($scope,$window, ApiUtil, ChoosePersonService, cfpLoadingBar){

            var depTree = null;
            $scope.allDep = {};
            $scope.depQuery = {};
            var checkSuccess = function(data){
	        	try {
	                return data['errCode'] == 0;
	            } catch (e) {
	                return false;
	            }
	        };
            var getWhat = ChoosePersonService.bindChooseWhat($scope.chooseWhat);
            for(var k in getWhat) {
                $scope[k] = getWhat[k];
            }

            /**
             * 判断id是否已经选择
             * @param id
             */
            function checkInitSelected(id) {
                for(var i=0; i<$scope.selectedList.length; i++){
                    if($scope.selectedList[i].de_wxid==id) {
                        return true;
                    }
                }
                return false;
            }

            /**
             * 用户取消选择时，情况已选择列表
             * @param id
             */
            function cleanInitSelected(id) {
                var i=0;
                for(; i<$scope.selectedList.length; i++){
                    if($scope.selectedList[i].id==id) {
                        break;
                    }
                }
                if(i<$scope.selectedList.length) {
                    $scope.selectedList.splice(i,1);
                }
            }
            function eachTreeNode(nodeList, childField, fn) {
		        if(nodeList instanceof Array){
		            for(var dli=0; dli<nodeList.length; dli++) {
		                var itDep = nodeList[dli];
		                fn && fn(itDep);
		                if(itDep[childField]) {
		                    eachTreeNode(itDep[childField], childField, fn);
		                }
		            }
		        }
		    }

            /**
             * 初始化遍历部门list
             */
            var init = function initFun(){
                cfpLoadingBar.start();
                $scope.departmentList = ChoosePersonService.department(/*{_identifier:$window.application_info.identifier}*/).then(function (data) {
                    cfpLoadingBar.complete();
                    if(checkSuccess(data)) {
                        depTree = $scope.departmentList = data.result.list;
                        eachTreeNode(data.result.list,'sub',function(dep){
                        	dep.isChecked = checkInitSelected(dep.de_wxid);
                            dep['number'] = dep.sub?dep.sub.length:0;
                        	dep.noChild = true;
	                        if(dep.sub) { 
	                            dep.noChild = false;
	                        }
	                        $scope.allDep[dep.de_wxid] = dep;
                        });
                    }
                }, function (error) {
                    cfpLoadingBar.complete();
                    console.log("选人组件.请求部门信息错误", error)
                });

            };


            /**
             * 部分查询操作
             */
            $scope.depQuery = { };
            $scope.isSearchDep = false;
            // 显示隐藏子部门
            $scope.toggleDep = function (id) {

                // 已经加载过数据，不再加载
                $scope.allDep[id].isOpen = !$scope.allDep[id].isOpen;
                if(($scope.allDep[id].sub && $scope.allDep[id].sub.length>0) || $scope.allDep[id].noChild) {
                    return;
                }

                $scope.depQuery.de_wxid = id;
                //$scope.depQuery._identifier=$window.application_info.identifier;
                $scope.allDep[id]['number'] = 0;
                cfpLoadingBar.start();
                ChoosePersonService.department($scope.depQuery).then(function (data) {
                    cfpLoadingBar.complete();
                    if(checkSuccess(data)) {
                        if(data.result.list.length>0) {
                            for(var index in data.result.list) {
                                var dep = data.result.list[index];
                                var have = $scope.allDep.hasOwnProperty(dep.de_wxid);
                                dep['de_parentid'] = id;
                                dep['parent_id'] = id;
                                dep['isChecked'] = checkInitSelected(dep.de_wxid)  // 用户之前已经选择
                                    || $scope.allDep[de_wxid]['isChecked']         // 上级部门选中状态
                                    || (have && $scope.allDep[dep.de_wxid].isChecked); // 用户通过搜索过后的选中状态

                                $scope.allDep[dep.de_wxid] = dep;
                            }
                            $scope.allDep[de_wxid].sub = data.result.list;

                            if( $scope.allDep[de_wxid]['isChecked'] ){
                                var get_Child_len =  $scope.allDep[id].sub.length;
                                $scope.allDep[id]['number'] = get_Child_len;
                            }

                        } else {
                            $scope.allDep[id].noChild = true;
                        }
                    }
                }, function (error) {
                    cfpLoadingBar.complete();
                    console.log("选人组件.请求部分信息错误", error)
                });
            };


            /**
             * 子部门 递归
             * @param node
             * @param isChecked
             */
            function childProcess(node, isChecked) {
                node['isChecked'] = isChecked;
                node.number = 0;
                if(node.sub) {
                    for(var index in node.sub) {
                        childProcess(node.sub[index], isChecked);
                    }
                }
            }

            /**
             * 父部门递归
             * @param node
             * @param isChecked
             */
            function parentProcess(node, isChecked) {
                if (isChecked == true) {
                    node.number++;
                } else {
                    node.number--;
                }
                (node.number == node.sub.length) ? node['isChecked'] = true : node['isChecked'] = false;
                if(node.de_parentid) {
                    parentProcess($scope.allDep[node.de_parentid], isChecked)
                }
            }

            /**
             * 点击部门，设置部门选择状态
             *
             * @param id
             */
            $scope.selectDepartment = function (id) {
                var dep = $scope.allDep[id];

                dep['isChecked'] = !dep.isChecked;
                if(!dep.hasOwnProperty('number')){
                    dep['number'] = 0;
                }

                if(!dep['isChecked']) {
                    cleanInitSelected(dep.de_wxid);
                }

                // 处理搜索操作时的对象
                if($scope.isSearchDep) {
                    for(var index=0;index<$scope.departmentList.length; index++) {
                        if($scope.departmentList[index].de_wxid == id) {
                            $scope.departmentList[index].isChecked = !$scope.departmentList[index].isChecked
                        } /*单选处理*/else if($scope.singleSelect) {
                            $scope.departmentList[index].isChecked = false;
                        }
                    }
                }

                /* 单选处理：清楚其它选择项 */
                if($scope.singleSelect && dep.isChecked) {
                    for(var k in $scope.allDep) {
                        if(k!=id) {
                            $scope.allDep[k].isChecked = false;
                            //$scope.allDep[k] = false;
                        }
                    }
                }

                if(dep.sub && !$scope.isSearchDep&&dep.isOpen)  {
                    // 递归子部门
                    for(var index in dep.sub) {
                        childProcess(dep.sub[index], dep['isChecked']);
                    }
                }
                // TODO [现在不要操作上级部门] 递归子部门
                //if(dep.parentDep_id) {
                //    parentProcess($scope.allDep[dep.parentDep_id], dep['isChecked']);
                //}

            };

            /*
             * 计算选中的部门
             */
            function computeSelectedDepartment(tree) {

                var list = [];

                for(var key in tree) {
                    var dep = tree[key];
                    if(dep['isChecked']) {
                        list.push(dep);
                    } /*else TODO 返回所有部门，现在需求是：选择部门并不一定会选中下面的子部门  if(dep.childDep) {
                     var childList = computeSelectedDepartment(dep.childDep);
                     childList.forEach(function (item) {
                     list.push(item);
                     })
                     }
                     */
                }

                return list;
            }

            /**
             * 确认选择
             * @constructor
             */
            $scope.OK = function () {
                $scope.doOk(computeSelectedDepartment($scope.allDep));
            };

            /**
             * 对于用户确定部门选择完成操作，需要在所有部门【$scope.allDep】中遍历查找
             * @param event
             */
            $scope.checkSearchDep = function (event) {
                if(!$scope.depQuery.keyword) {
                    // 没有搜索内容
                    return;
                }
                $scope.depQuery.de_wxid = null;
                if(event.keyCode==13) { // 输入enter键
                    cfpLoadingBar.start();
                    ChoosePersonService.department($scope.depQuery).then(function (data) {
                        cfpLoadingBar.complete();
                        if(checkSuccess(data)) {
                            $scope.departmentList = data.result.list;
                            for(var i in $scope.departmentList) {
                                var dep = $scope.departmentList[i];
                                var have = $scope.allDep.hasOwnProperty(dep.de_wxid);
                                dep.noChild = true;
                                dep.isChecked = checkInitSelected(dep.de_wxid) ||
                                    (have && $scope.allDep[dep.de_wxid].isChecked);
                                // 新对象保存到缓存中
                                if(!have) {
                                    $scope.allDep[dep.de_wxid] = JSON.parse(JSON.stringify(dep));
                                }
                            }
                        }
                        $scope.isSearchDep = true;
                    }, function (error) {
                        cfpLoadingBar.complete();
                        console.log("选人组件.请求部分信息错误", error)
                    });

                }
            };

            /**
             * 取消搜索部门
             */
            $scope.cancelSearchDep = function () {
                $scope.departmentList = depTree;
                $scope.depQuery.kw = null;
                $scope.isSearchDep = false;
            };

            init();

        }]);
    /**
     * 选部门组件对外服务
     */
    app.factory('DepartmentChooser', ['$q','$modal',function ($q,$modal) {
        return {
            choose: function (selected,size,params) {
                var defer = $q.defer();
                var modalInstance = $modal.open({
                    templateUrl: 'templates/choose-department.html',
                    size: size || 'lg',
                    resolve: {
                        selected: function () {
                            return selected?JSON.parse(JSON.stringify(selected)):null;
                        },
                        params: function () {
                            return params || {};
                        }
                    },
                    controller:['$scope', '$modalInstance','selected','params',function ($scope, $modalInstance, selected,params) {
                        for(var k in params) {
                            $scope[k] = params[k];
                        }

                        $scope.selectedList = selected;

                        $scope.doOk = function (res) {
                            $modalInstance.close(res);
                        };
                        $scope.doCancel = function (res) {
                            $modalInstance.dismiss(res || 'cancel');
                        };
                    }]
                });

                modalInstance.opened.then(function(){//模态窗口打开之后执行的函数
                    //console.log('modal is opened');
                });
                modalInstance.result.then(function (result) {
                    defer.resolve(result);
                }, function (reason) {
                    defer.reject(reason);
                });

                return { result:defer.promise };
            }
        };
    }]);

    app.controller('ChooseShimCtrl', ['$scope', 'PersonChooser','DepartmentChooser', function ($scope, PersonChooser, DepartmentChooser) {
        /**
         * 解析用户的参数
         * @param paramName
         * @returns {{selected: Object}}
         */
        function calShimParams(paramName) {
            var shimParams = eval(paramName);
            var selected = [];
            var config = {
                singleSelect:false
            };
            if(shimParams instanceof Array) {
                selected = shimParams;
            } else {
                for(var k in config) {
                    config[k] = shimParams.hasOwnProperty(k)?shimParams[k]:config[k];
                }
                selected = shimParams.hasOwnProperty('selected')?shimParams['selected']:[];
            }
            return {
                selected:selected,
                config: config
            };
        }
        /**
         * 选人ctrl
         */
        $scope.selectPerson = function(selectedPerson, callback, customParams) {
            var shimParams = calShimParams(selectedPerson);
            PersonChooser.choose(shimParams.selected,null,shimParams.config).result.then(function (data) {
                var fun = eval(callback);
                fun(data,customParams);
            });
        };
        /**
         * 选部门ctrl
         */
        $scope.selectDepartment = function(selectedDepartment, callback,customParams) {
            var shimParams = calShimParams(selectedDepartment);
            DepartmentChooser.choose(shimParams.selected,null,shimParams.config).result.then(function (data) {
                var fun = eval(callback);
                fun(data,customParams);
            });
        };
    }]);
    /**
     * 使用原始事件调用
     * @type {null}
     */
    var ShimApp = (function () {
        var app = null;
        return function () {
            if(!app) {
                app = angular.bootstrap(angular.element('<div></div>'),['ng-chooser']);
                //angular.injector(['ng', 'ng.poler.plugins.pc']);
            }
            return app;
        }
    })();

    window.shimChoosePerson = function (selectedPerson,config, callbackFun) {
        ShimApp().invoke(['$q', 'PersonChooser', function ($q, PersonChooser) {
            PersonChooser.choose(selectedPerson,null,config).result.then(function (data) {
                    callbackFun(data);
                });
        }]);
    };

    window.shimChooseDepartment = function (selectedDepartment,config, callbackFun) {
        ShimApp().invoke(['$q','DepartmentChooser', function ($q, DepartmentChooser) {
            DepartmentChooser.choose(selectedDepartment,null,config).result.then(function (data) {
                callbackFun(data);
            });
        }]);
    };


    window.advancedChoose = function(selecteds, config, callbackFun) {
        ShimApp().invoke(['AdvancedChooser', function(AdvancedChooser) {
            AdvancedChooser.choose(selecteds, null, config).result.then(function (data) {
                callbackFun(data);
            });
        }]);
    };

    /**
     * 配置接口url地址
     */
    window.ChooseApiConfig = function (conf) {
        ShimApp().invoke(['ApiUtil', function (ApiUtil) {
            ApiUtil.config({
                URL_PREFIX: conf.hostPath
            })
        }]);
    }
})(window, document, window.angular);